﻿using System;
using System.Collections.Generic;
using System.Text;
using ShapeMergeFactory;
using System.Threading;

namespace MapMerge
{
    class FileMergeFactory
    {
        private MergeFactory shapeMergeFactory;
        private string resultFilePath;
        private List<string> mergeFilePaths;
        private int finishedMergeNumber;
        private bool stopMerge;

        public event EventHandler<EventArgs> MergingFiles;
        public event EventHandler<EventArgs> MergeFinished;

        public FileMergeFactory()
        {
            shapeMergeFactory = new MergeFactory();
            mergeFilePaths = new List<string>();
            stopMerge = false;
            finishedMergeNumber = 0;
        }

        public void StartMerge(List<string> mergeFilePaths,string resultFilePath)
        {
            this.mergeFilePaths = mergeFilePaths;
            this.resultFilePath = resultFilePath;
            finishedMergeNumber = 0;
            stopMerge = false;
            shapeMergeFactory.BuildResultFile(resultFilePath);
            new Thread(MergeThread).Start();

        }

        protected virtual void OnMergingFiles()
        {
            MergingFiles(this,new EventArgs());
        }

        protected virtual void OnMergeFinished()
        {
            MergeFinished(this,new EventArgs());
        }

        private void MergeThread()
        {
            while (!stopMerge&&finishedMergeNumber<mergeFilePaths.Count)
            {
                OnMergingFiles();
                shapeMergeFactory.MergeShapeHeadAndRecord(mergeFilePaths[finishedMergeNumber],resultFilePath);
                ++finishedMergeNumber;
            }
            if (finishedMergeNumber==mergeFilePaths.Count&&stopMerge==false)
            {
                stopMerge = true;
                OnMergeFinished();
            }
        }

        public int GetMergePercent()
        {
            return finishedMergeNumber / mergeFilePaths.Count * 100;
        }
    }
}
